<?php

namespace App\Repositories\Company;

use App\Models\CagetoryModel;
use App\Models\CompanyOptionModel;
use App\Models\CompanysModel;
use App\Models\User\UserModel;
use App\Models\Main\ComProductModel;

class CompanyRepository
{
    protected $cagetoryModel;
    protected $companysModel;
    protected $companyOptionModel;
    protected $user;
    protected $companyProductModel;
    static $EARTH_RADIUS = 6371;

    public function __construct()
    {
        $this->cagetoryModel = new CagetoryModel;
        $this->companysModel = new CompanysModel;
        $this->companyOptionModel = new CompanyOptionModel;
        $this->user = new UserModel;
        $this->companyProductModel = new ComProductModel();
    }

    public function getCompanyCagetory($pid = 0)
    {
        $result = $this->cagetoryModel->select('id', 'name')->where(['pid' => $pid, 'del' => 0])->get();
        if ($result->isEmpty()) {
            return [];
        }
        return $result->toArray();
    }

    /**
     * 根据IDs获取企业信息
     * @param array $ids
     * @return array
     */
    public function getCompanyByIds($ids = [])
    {
        $result = $this->companysModel->where('cate', 1)->whereIn('id', $ids)->orderBy('created_at', 'desc')->get();
        if ($result->isEmpty()) {
            return [];
        }
        return $result->toArray();
    }
    public function getCompanyInfoById($uid){
        $result = $this->companysModel->where("uid",$uid)->get([
            "uid","com_name","com_tel","com_fax","com_address",
            "com_city","quality","out_type","age_range","lat",
            "lng","detail","cus_like","pact"
            ]);
        return $result->toArray();
    }

    /**
     * zwp
     * 获取对应用户uid的法人信息
     * * @param integer $uid
     * @return array
     */
    public function getLegalById($uid = null){
        $result = $this->companysModel->where('uid',$uid)->get(["uid","legal_name","legal_sex","legal_mobile","legal_idcard","legal_idcard_imgs"]);
        return $result->toArray();
    }
    /**
     * zwp
     * 保存对应用户uid的法人信息
     *  @param array $data
     * @return bool
     */
    
    public function saveLegalInfoById($uid,$data){
        return $this->saveAllInfoById($uid,$data);
    }
     /**
     * zwp
     * 保存对应用户uid的公司信息
     *  @param array $data
     * @return bool
     */
     public function saveCompanyInfoById($uid,$data){
        return $this->saveAllInfoById($uid,$data);
     }
     /**
     * zwp
     * 保存对应用户uid的信息到users_companys表
     *  @param array $data
     * @return bool
     */
     public function saveAllInfoById($uid,$data){
         $flag = $this->companysModel->where("uid",$uid)->update($data);
        if(!$flag){
            return false;
        }
        return true;
     }
     /**
      * zwp
      * 获取公司认证资料，
      * @param type $uid
      * @return type
      */
     public function getLicencesById($uid){
         $data = $this->companyOptionModel->where("uid",$uid)->get(["uid","legal_licences","com_licences"]);
         return $data->toArray();
     }
     /**zwp
      * 保存证件信息
      * @param array $data
      * @return boolean
      */
     public function saveLicences($uid,$data){
         $flag = $this->companyOptionModel->where("uid",$uid)->update([$data]);
         if(!$flag){
             return false;
         }
         return true;
     }
     /**zwp
      * 返回公司id
      * @param integer $uid
      * @return integer
      */
     public function getCid($uid){
         $cid = $this->companysModel->where("uid",$uid)->first();
         if(!$cid){
             return null;
         }
         return $cid->id;
     }
     /**zwp
      * 获取公司产品
      * @param integer $cid
      * @return array
      */
     
     public function getCompanyProductsByCid($cid){
         $data = $this->companyProductModel->
                 where(["cid"=>$cid,"del"=>0])->
                 get(["id","cid","genre","type","cate","del","created_at"]);
         
         return $data->toArray();
     }
     
     /**zwp
      * 获取分类表对应名称
      * @param integer $cate 分类Id
      * @return string
      */
     public function getCateName($cate){
         
         $data = $this->cagetoryModel->where("id",$cate)->first();
         $data = $data->toArray();
         $name = $data["name"];
         /*
         $pid = $data["pid"];
         $cateName = $this->getParentName($pid);
         $cateName = $cateName.$name;
         */
         return $name;
     }
     /**zwp
      * 获取分类表父级名称
      * @param integer $pid
      * @return string
      */
     public function getParentName($pid){
         $name = "";
         while($pid!=0){
            $data = $this->cagetoryModel->where("id",$pid)->first();
            $data = $data->toArray();
            $pid = $data["pid"];
            $name = $data["name"]."|".$name;
            
         }
         return $name;
     }

     public function sort($name){
     }
     /**zwp
      * 获取子级，就是最下级分类名称
      * @param integer $cate
      * @return array
      */
     public function getDataFromCate($cate){
         $data = $this->cagetoryModel->where("id",$cate)->first();
         if(!$data){
             return null;
         }
         return $data->toArray();
     }
     /**zwp
      * 获取pid为0的分类名称
      * @param integer $id
      * @return array
      */
     public function getStyleByZeroPid($id){
         $data = $this->cagetoryModel->where("id",$id)->first();
         return $data->toArray();
     }

     /**zwp
      * 获取最前面的，就是顶级分类名称
      * @param integer $pid
      * @return string
      */
     public function getStyleByPid($pid){
         $name = "";
         
         while($pid!=0){
            $data = $this->cagetoryModel->where("id",$pid)->first();
            $data = $data->toArray();
            $pid = $data["pid"];
            $name = $data["name"];
         }
         return $name;
     }
     /**zwp
      * 通过用户id获取产品风格
      * @param integer $uid
      * @return array
      */
     public function getStyleByUid($uid){
         $data = $this->companyOptionModel->where("uid",$uid)->first();
         return $data->toArray();
     }
     /**zwp
      * 获取分类
      * @param integer $id
      * @return array
      */
     
     public function getCateByStyleId($id){
         $data = $this->cagetoryModel->where("id",$id)->first();
         if(!$data){
             return null;
         }
         return $data->toArray();
     }
     /**zwp
      * 保存产品修改
      * @param array $data
      */
     public function saveCompanyProducts($data){
         foreach ($data as $value){
             $this->companyProductModel->where("id",$value["id"])->update($value);
         }
         
     }
     
     public function saveStyle($uid,$data){
         return $this->companyOptionModel->where("uid",$uid)->update(["styles"=>$data]);
     }
     
     public function getProTypes($uid){
         $data = $this->companyOptionModel->where("uid",$uid)->first();
         return $data->toArray();
     }
     
     public function saveProTypes($uid,$data){
         return $this->companyOptionModel->where("uid",$uid)->update(["pro_types"=>$data]);
     }

     public function getDesigns($uid){
         return $this->getProTypes($uid);
     }
     
     public function saveDesigns($uid,$data){
         return $this->companyOptionModel->where("uid",$uid)->update(["designs"=>$data]);
     }
     public function insertName($name){
         return $this->cagetoryModel->insert(["name"=>$name]);
     }

    public function hasName($name){
        $flag = $this->cagetoryModel->where("name",$name)->first();
        return $flag;
    }
    public function getYields($uid){
        $data = $this->companyOptionModel->where("uid",$uid)->first();
        return $data->toArray();
    }
    public function saveYields($uid,$data){
        return $this->companyOptionModel->where("uid",$uid)->update($data);
    }
    public function getEnvs($uid){
        $data = $this->companyOptionModel->where("uid",$uid)->first();
        return $data->toArray();
    }
    public function saveEnvs($uid,$data){
        return $this->companyOptionModel->where("uid",$uid)->update($data);
    }

    /**
     * 根据经纬度查询附近企业
     * @param $lat
     * @param $lng
     * @param $distance
     * @return array
     */
    public function getCompanyByLatLng($lat, $lng, $distance)
    {
        if (empty($lat) || empty($lng)) {
            return [];
        }
        $squares = $this->returnSquarePoint($lng, $lat, $distance);

        $companys = $this->companysModel
            ->where('lat', '!=', 0)
            ->where('lat', '>', $squares['right-bottom']['lat'])
            ->where('lat', '<', $squares['left-top']['lat'])
            ->where('lng', '>', $squares['left-top']['lng'])
            ->where('lng', '<', $squares['right-bottom']['lng'])
            ->orderBy('created_at', 'desc')
            ->pluck('id');
        return $companys->isEmpty() ? [] : $companys->toArray();
    }

    /**
     *计算某个经纬度的周围某段距离的正方形的四个点
     *
     * @param lng float 经度
     * @param lat float 纬度
     * @param distance float 该点所在圆的半径，该圆与此正方形内切，默认值为0.5千米
     * @return array 正方形的四个点的经纬度坐标
     */
    public function returnSquarePoint($lng, $lat, $distance = 0.5)
    {

        $dlng = 2 * asin(sin($distance / (2 * self::$EARTH_RADIUS)) / cos(deg2rad($lat)));
        $dlng = rad2deg($dlng);

        $dlat = $distance / self::$EARTH_RADIUS;
        $dlat = rad2deg($dlat);

        return array(
            'left-top' => array('lat' => $lat + $dlat, 'lng' => $lng - $dlng),
            'right-top' => array('lat' => $lat + $dlat, 'lng' => $lng + $dlng),
            'left-bottom' => array('lat' => $lat - $dlat, 'lng' => $lng - $dlng),
            'right-bottom' => array('lat' => $lat - $dlat, 'lng' => $lng + $dlng)
        );
    }


    public function getCreateCompanyMustParamRules()
    {
        return [
            'uid' => 'required',
            'cate' => 'required',
            'legal_name' => 'required',
            'legal_sex' => 'required|in:1,2,3',
            'legal_mobile' => 'required',
            'legal_idcard' => 'required',
            'legal_idcard_imgs' => 'required',
            'com_name' => 'required',
            'com_tel' => 'required',
            'com_fax' => 'required',
            'com_address' => 'required',
            'com_city' => 'required',
            'cus_like' => 'required',
            'quality' => 'required',
            'pact' => 'required',
            'param' => 'required',
            'param2' => 'required',
            'out_type' => 'required',
            'age_range' => 'required',
            'detail' => 'required',
            'lat' => 'required',
            'lng' => 'required',
            'created_at' => 'required',
            'updated_at' => 'required',
        ];
    }

    public function getCreateCompanyReloadNeedParams()
    {
        return [
            'uid',
            'cate',
            'legal_name',
            'legal_sex',
            'legal_mobile',
            'legal_idcard',
            'legal_idcard_imgs',
            'com_name',
            'com_tel',
            'com_fax',
            'com_address',
            'com_city',
            'cus_like',
            'quality',
            'pact',
            'param',
            'param2',
            'out_type',
            'age_range',
            'detail',
            'lat',
            'lng'
        ];
    }

    public function getCreateCompanyOptionReloadNeedParams()
    {
        return [
            'uid',
            'lagel_licences',
            'com_licences',
            'products',
            'styles',
            'pro_types',
            'fashions',
            'equips',
            'capacity_departments',
            'capacity_outputs',
            'require_products',
            'require_departs',
            'require_standards',
            'envs'
        ];
    }

    public function addCompany($uid, $type, $companyData, $companyOptionData)
    {
        $ti = time();
        $this->companysModel->setRawAttributes($companyData);
        $this->companysModel->setAttribute('created_at', $ti);
        $this->companysModel->setAttribute('updated_at', $ti);
        $this->companysModel->save();

        $this->companyOptionModel->setRawAttributes($companyOptionData);
        $this->companyOptionModel->setAttribute('created_at', $ti);
        $this->companyOptionModel->setAttribute('updated_at', $ti);
        $this->companyOptionModel->save();

        $this->user->query()->where('id', '=', $uid)->first()->setAttribute('type', $type)->save();
    }

    public function getAllCompanyByCate($cate_id)
    {
        $data = $this->companysModel->newQuery()->where(['cate' => 1])->where(['facType' => $cate_id])->select(['id', 'uid', 'com_name'])->get()->toArray();
        $userIds = empty($data) ? [] : array_column($data, 'uid');
        $userData = $this->user->newQuery()->where('id', 'in', $userIds)->select(['id', 'head'])->get()->toArray();
        if (!empty($userData)) {
            $userData = array_column($userData, 'head', 'id');
        }

        foreach ($data as $k => $v) {
            $data[$k]['img'] = empty($userData) || empty($userData[$v['uid']]) ? '/uploads/20190227/companyone.png' : $userData[$v['uid']];
        }

        return $data;
    }

    //客户分类
    public function customerCate()
    {
        $factoryCate = $this->getCompanyCagetory(1);
        $companyCate = [];
        return array_merge($factoryCate, $companyCate);
    }

    //企业详情（客户详情）
    public function companyDetail($id)
    {
        $data = [
//            'products' => [], //服务，二维组数，json  male男，female女，child童
            'legal_name' => '', //法人姓名,
            'legal_sex' => 0,//法人性别
            'legal_mobile' => '',//法人常用手机号码
            'legal_id_photo' => [], //身份证招聘下表 分别对应：正面、反面、手持正面
            'com_name' => '',//公司名称
            'com_tel' =>'',//公司座机
            'com_fax' => '',//公司传真
            'com_address' => '',//公司地址
            'cus_like' => '',//公司满意度
            'quality' => '',//品质满意度
            'pact' => '',//合同履行率
            'legal_licences' => new \stdClass(),//法人认证照片：法人照片photo；身份证照片：idcard；毕业证照片：graduate；证书：honor；结婚证：marry；驾驶证：drive；
            'com_licences' => new \stdClass(),//公司认证：组织机构代码证：zzjgdm；营业执照：yyzz；税务登记证：swdj；租赁合同：rent；各类许可证：licence；荣誉证书：honor；房产证：house；
            'yields' => new \stdClass(),/*yields 产量产能，json：
                                depart 产能部门：生产线人数，检验组人数；
                                dayOutPut 日产量，件：最小产量，最大产量；
                                requirePro 质量要求：市场货，半精品，全精品，外销；
                                requireDepart 质量部门：产品类型、检验类型（几道检验）；
                                standards 质量标准：
                                    《工艺单》、样品，摊平用尺量用目视用手摸，质检：每件产品全检，
                                    总检：抽查品质、尺寸，巡检：对在线生产产品巡查
            */
            'envs' => new \stdClass(),
            /*
             * envs 工厂环境图片，二维数组，json
            managers 总经理，facManagers 厂长，finances 财务室，guards 门卫，
            shapes 厂房外形图，raws 充绒房，techs 技术部，works 缝制车间，
            backs 后道车间，cuts 裁剪车间，dorms 工厂宿舍，samples 样衣间，
     * envs 公司环境图片，二维数组，json
            managers 总经理，manager2s 副总经理，directors 总监，handles 总经办，
            finances 财务室，officers 行政部，sales 销售部，expands 拓展部，
            designs 设计部，buyers 采购部，sellers 电商部，produces 生产部，
            qcs 品控部，storages 仓储部，transports 物流部，outs 外发部，
            meetings 会议室，halls 展厅，stages 仓储部，talks 谈判室，
            cooks 厨房，wcs 厕所，teas 茶水间，dorms 宿舍，
             */
        ];

        $data1 = $this->companyOptionModel->newQuery()->where('uid', '=', $id)->first();
        if (!empty($data1)) {
            $data1 = $data1->toArray();
            if (!empty($data1['legal_licences'])) {
                $data['legal_licences'] = json_decode($data1['legal_licences'], true);
            }
            if (!empty($data1['yields'])) {
                $data['yields'] = json_decode($data1['yields'], true);
            }
            if (!empty($data1['envs'])) {
                $data['envs'] = json_decode($data1['envs'], true);
            }
        }
        $data2 = $this->companysModel->newQuery()->where('uid', '=', $id)->first();
        if (!empty($data2)) {
            $data2 = $data2->toArray();
            $data['legal_name'] = $data2['legal_name'];
            $data['legal_sex'] = $data2['legal_sex'];
            $data['legal_mobile'] = $data2['legal_mobile'];
            $id_photo = $data2['legal_idcard_imgs'];
            if (!empty($id_photo)) {
                $is_photo = explode('|', $id_photo);
                $data['legal_id_photo'] = $is_photo;
            }
            $data['com_name'] = $data2['com_name'];
            $data['com_tel'] = $data2['com_tel'];
            $data['com_fax'] = $data2['com_fax'];
            $data['com_address'] = $data2['com_address'];
            $data['cus_like'] = $data2['cus_like'];
            $data['quality'] = $data2['quality'];
            $data['pact'] = $data2['pact'];
        }
        return $data;
    }
}